package com.lg.algorithm.collections.queue.block;

import lombok.Getter;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 支持 延迟的 优先级队列

 如何保证线程安全
 ReentrantLock

 如何延迟
 reentrantLock.condition.awaitNanos(nanos)

 如何优先级
 PriorityQueue

 DelayQueue
 不可以指定大小，底层是 PriorityQueue，默认大小是11。扩容最大为Integer.MAX_VALUE
 初期PriorityQueue开辟空间为11的数组。
 使用lock.newCondition().await()进行阻塞
 */
public class DelayQueueTest {
    static class Obj implements Delayed {
        Obj(Integer value) {
            this.value = value;
        }
        @Getter
        Integer value;

        @Override
        public long getDelay(TimeUnit unit) {
            return 0;
        }

        @Override
        public int compareTo(Delayed o) {
            Obj oo = (Obj) o;
            return this.value > oo.getValue() ? 1 : -1;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Obj> delayeds = new DelayQueue<>();
        Obj obj = new Obj(1);
        Obj obj2 = new Obj(17);
        Obj obj3 = new Obj(13);
        Obj obj4 = new Obj(111);

        delayeds.put(obj);
        delayeds.put(obj2);
        delayeds.put(obj3);
        delayeds.put(obj4);
        delayeds.take();
        System.out.println(delayeds.poll().getValue());
        System.out.println(delayeds.poll().getValue());
        System.out.println(delayeds.poll().getValue());
        System.out.println(delayeds.poll().getValue());
        System.out.println(delayeds.poll().getValue());

    }
}
